<?php
// school/school_view.php
// عرض تفاصيل مدرسة — super_admin + general_supervisor
$page_title = 'عرض مدرسة';
require_once('../includes/header.php');
require_once('../includes/permissions.php');

/* ============================================================
   Polyfills
   ============================================================ */
if (!function_exists('h'))     { function h($s)     { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); } }
if (!function_exists('money')) { function money($n) { return number_format((float)$n, 2); } }

/* ============================================================
   ✅ الوصول — super_admin + general_supervisor
   ============================================================ */
if (empty($_SESSION['user_id'])) { http_response_code(403); exit('Forbidden'); }

$current_role = current_role();
$is_super     = is_super_admin();
$is_general   = is_general_supervisor();
$can_see      = ($is_super || $is_general);

if (!$can_see) {
    echo '<div class="alert alert-error">🔒 هذه الصفحة متاحة للمشرف العام ومدير النظام فقط.</div>';
    require_once('includes/footer.php');
    exit;
}

/* ============================================================
   GET — معرّف المدرسة
   ============================================================ */
$school_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($school_id <= 0) {
    echo '<div class="alert alert-error">❌ معرّف المدرسة غير صالح.</div>';
    require_once('includes/footer.php');
    exit;
}

/* ============================================================
   اكتشاف أعمدة الجداول
   ============================================================ */
$SCHOOL_COLS = array();
$r = @mysqli_query($conn, "SHOW COLUMNS FROM schools");
if ($r) while ($row = mysqli_fetch_assoc($r)) $SCHOOL_COLS[] = $row['Field'];
$HAS_SCHOOL = function($c) use ($SCHOOL_COLS) {
    return in_array($c, $SCHOOL_COLS, true);
};

/* ============================================================
   جلب بيانات المدرسة
   ============================================================ */
$stmt = mysqli_prepare($conn, "SELECT * FROM schools WHERE school_id = ? LIMIT 1");
mysqli_stmt_bind_param($stmt, 'i', $school_id);
mysqli_stmt_execute($stmt);
$r = mysqli_stmt_get_result($stmt);
$school = $r ? mysqli_fetch_assoc($r) : null;
mysqli_stmt_close($stmt);

if (!$school) {
    echo '<div class="alert alert-error">❌ المدرسة غير موجودة.</div>';
    require_once('includes/footer.php');
    exit;
}

/* ============================================================
   إحصائيات شاملة
   ============================================================ */
$stats = array(
    'students'      => 0,
    'students_m'    => 0,
    'students_f'    => 0,
    'classes'       => 0,
    'sections'      => 0,
    'teachers'      => 0,
    'fees_total'    => 0,
    'fees_paid'     => 0,
    'fees_unpaid'   => 0,
);

// الطلاب
$r = @mysqli_query($conn,
    "SELECT COUNT(*) AS cnt FROM students WHERE school_id = " . (int)$school_id);
if ($r && $row = mysqli_fetch_assoc($r)) $stats['students'] = (int)$row['cnt'];

$r = @mysqli_query($conn,
    "SELECT COUNT(*) AS cnt FROM students WHERE school_id = " . (int)$school_id
    . " AND gender = 'M'");
if ($r && $row = mysqli_fetch_assoc($r)) $stats['students_m'] = (int)$row['cnt'];

$r = @mysqli_query($conn,
    "SELECT COUNT(*) AS cnt FROM students WHERE school_id = " . (int)$school_id
    . " AND gender = 'F'");
if ($r && $row = mysqli_fetch_assoc($r)) $stats['students_f'] = (int)$row['cnt'];

// الفصول
$r = @mysqli_query($conn,
    "SELECT COUNT(*) AS cnt FROM classes WHERE school_id = " . (int)$school_id);
if ($r && $row = mysqli_fetch_assoc($r)) $stats['classes'] = (int)$row['cnt'];

// المراحل
$SECTIONS_TABLE = null;
foreach (array('sections','divisions','class_sections') as $t) {
    $rr = @mysqli_query($conn, "SHOW TABLES LIKE '$t'");
    if ($rr && mysqli_num_rows($rr) > 0) { $SECTIONS_TABLE = $t; break; }
}
if ($SECTIONS_TABLE) {
    $r = @mysqli_query($conn,
        "SELECT COUNT(*) AS cnt FROM `$SECTIONS_TABLE` WHERE school_id = " . (int)$school_id);
    if ($r && $row = mysqli_fetch_assoc($r)) $stats['sections'] = (int)$row['cnt'];
}

// الرسوم (student_fees)
$r = @mysqli_query($conn,
    "SELECT 
        IFNULL(SUM(sf.amount - sf.discount), 0) AS total,
        IFNULL(SUM(sf.paid_amount), 0) AS paid
     FROM student_fees sf
     JOIN students s ON s.student_id = sf.student_id
     WHERE s.school_id = " . (int)$school_id);
if ($r && $row = mysqli_fetch_assoc($r)) {
    $stats['fees_total']  = (float)$row['total'];
    $stats['fees_paid']   = (float)$row['paid'];
    $stats['fees_unpaid'] = $stats['fees_total'] - $stats['fees_paid'];
}

/* ============================================================
   قائمة المراحل
   ============================================================ */
$sections_list = array();
if ($SECTIONS_TABLE) {
    $r = @mysqli_query($conn,
        "SELECT * FROM `$SECTIONS_TABLE` 
         WHERE school_id = " . (int)$school_id . "
         ORDER BY " . (in_array('sort_order', array_column(
             mysqli_fetch_all(mysqli_query($conn, "SHOW COLUMNS FROM `$SECTIONS_TABLE`"), MYSQLI_ASSOC),
             'Field')) ? 'sort_order, ' : '') . " section_id ASC");
    if ($r) while ($row = mysqli_fetch_assoc($r)) $sections_list[] = $row;
}

/* ============================================================
   قائمة الفصول
   ============================================================ */
$classes_list = array();
$r = @mysqli_query($conn,
    "SELECT c.*, 
            (SELECT COUNT(*) FROM students s WHERE s.class_id = c.class_id) AS students_count
     FROM classes c 
     WHERE c.school_id = " . (int)$school_id . "
     ORDER BY c.class_name");
if ($r) while ($row = mysqli_fetch_assoc($r)) $classes_list[] = $row;

/* ============================================================
   أحدث الطلاب المضافين
   ============================================================ */
$recent_students = array();
$r = @mysqli_query($conn,
    "SELECT * FROM students 
     WHERE school_id = " . (int)$school_id . "
     ORDER BY student_id DESC LIMIT 5");
if ($r) while ($row = mysqli_fetch_assoc($r)) $recent_students[] = $row;

/* ============================================================
   دالة مساعدة لعرض الاسم الكامل
   ============================================================ */
if (!function_exists('student_full_name_view')) {
    function student_full_name_view($row) {
        if (!empty($row['full_name'])) return $row['full_name'];
        $parts = array();
        foreach (array('first_name','second_name','third_name','fourth_name') as $k) {
            if (!empty($row[$k])) $parts[] = $row[$k];
        }
        if ($parts) return implode(' ', $parts);
        return trim(
            (isset($row['firstname']) ? $row['firstname'] : '') . ' ' .
            (isset($row['lastname'])  ? $row['lastname']  : '')
        );
    }
}
?>
<?php require_once('includes/sidebar.php'); ?>

<style>
/* ═══════════════════════════════════════════════════════════
   رأس المدرسة
   ═══════════════════════════════════════════════════════════ */
.school-header {
    background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
    padding: 28px 30px;
    border-radius: 20px;
    color: white;
    margin-bottom: 20px;
    display: flex;
    gap: 24px;
    align-items: center;
    flex-wrap: wrap;
    box-shadow: 0 10px 30px rgba(59,130,246,0.25);
}
.school-logo {
    width: 100px;
    height: 100px;
    border-radius: 20px;
    background: rgba(255,255,255,0.2);
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    border: 3px solid rgba(255,255,255,0.3);
    flex-shrink: 0;
}
.school-logo img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
}
.school-logo .placeholder {
    font-size: 3rem;
}
.school-header-info {
    flex: 1;
    min-width: 250px;
}
.school-header-info h1 {
    margin: 0 0 8px 0;
    font-size: 1.8rem;
    font-weight: 700;
    color: white;
}
.school-header-meta {
    display: flex;
    gap: 16px;
    flex-wrap: wrap;
    font-size: 0.9rem;
    opacity: 0.95;
}
.school-header-meta span {
    display: inline-flex;
    align-items: center;
    gap: 4px;
}
.status-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
    background: rgba(255,255,255,0.25);
    color: white;
}
.status-badge.active {
    background: #10b981;
}
.status-badge.inactive {
    background: #ef4444;
}

/* ═══════════════════════════════════════════════════════════
   بطاقات الإحصائيات
   ═══════════════════════════════════════════════════════════ */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 12px;
    margin-bottom: 20px;
}
.stat-card {
    padding: 18px 20px;
    border-radius: 14px;
    background: white;
    border: 1.5px solid #e2e8f0;
    position: relative;
    overflow: hidden;
}
.stat-card::before {
    content: '';
    position: absolute;
    top: 0; right: 0;
    width: 5px;
    height: 100%;
}
.stat-card.blue::before   { background: #3b82f6; }
.stat-card.green::before  { background: #10b981; }
.stat-card.orange::before { background: #f59e0b; }
.stat-card.red::before    { background: #ef4444; }
.stat-card.purple::before { background: #8b5cf6; }
.stat-card.pink::before   { background: #ec4899; }

.stat-icon {
    font-size: 1.5rem;
    margin-bottom: 6px;
    opacity: 0.8;
}
.stat-value {
    font-size: 1.8rem;
    font-weight: 700;
    color: #1e293b;
    line-height: 1.1;
    direction: ltr;
}
.stat-label {
    font-size: 0.85rem;
    color: #64748b;
    margin-top: 4px;
    font-weight: 500;
}
.stat-sub {
    font-size: 0.72rem;
    color: #94a3b8;
    margin-top: 6px;
}

/* ═══════════════════════════════════════════════════════════
   البطاقات
   ═══════════════════════════════════════════════════════════ */
.info-card {
    background: white;
    border-radius: 14px;
    border: 1.5px solid #e2e8f0;
    padding: 20px 24px;
    margin-bottom: 16px;
}
.info-card h4 {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 1.05rem;
    font-weight: 600;
    color: #1e293b;
    margin: 0 0 16px 0;
    padding-bottom: 12px;
    border-bottom: 2px solid #f1f5f9;
}
.info-row {
    display: flex;
    padding: 10px 0;
    border-bottom: 1px solid #f8fafc;
    align-items: flex-start;
}
.info-row:last-child { border-bottom: none; }
.info-label {
    width: 160px;
    flex-shrink: 0;
    font-weight: 500;
    color: #64748b;
    font-size: 0.9rem;
    display: flex;
    align-items: center;
    gap: 6px;
}
.info-value {
    flex: 1;
    color: #1e293b;
    font-weight: 500;
    word-wrap: break-word;
    font-size: 0.95rem;
}
.info-value.muted {
    color: #94a3b8;
    font-weight: 400;
}
.info-value a {
    color: #3b82f6;
    text-decoration: none;
}
.info-value a:hover { text-decoration: underline; }

/* ═══════════════════════════════════════════════════════════
   الجداول
   ═══════════════════════════════════════════════════════════ */
.data-table {
    width: 100%;
    border-collapse: collapse;
}
.data-table thead th {
    padding: 12px 10px;
    background: #f8fafc;
    color: #475569;
    font-weight: 600;
    font-size: 0.85rem;
    border-bottom: 2px solid #e2e8f0;
    text-align: right;
    white-space: nowrap;
}
.data-table tbody td {
    padding: 10px;
    border-bottom: 1px solid #f1f5f9;
    font-size: 0.9rem;
    color: #334155;
    vertical-align: middle;
}
.data-table tbody tr:hover { background: #f8fafc; }
.data-table tbody tr:last-child td { border-bottom: none; }

/* ═══════════════════════════════════════════════════════════
   أزرار الإجراءات
   ═══════════════════════════════════════════════════════════ */
.action-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 10px;
    margin-bottom: 20px;
}
.action-btn {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 14px 16px;
    background: white;
    border: 1.5px solid #e2e8f0;
    border-radius: 12px;
    text-decoration: none;
    color: #334155;
    font-weight: 500;
    font-size: 0.9rem;
    transition: all 0.15s;
    cursor: pointer;
}
.action-btn:hover {
    border-color: #3b82f6;
    background: #eff6ff;
    color: #1e40af;
    transform: translateY(-2px);
    box-shadow: 0 6px 15px rgba(59,130,246,0.15);
}
.action-btn .icon {
    font-size: 1.4rem;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f1f5f9;
    border-radius: 8px;
}
.action-btn:hover .icon {
    background: #dbeafe;
}
.action-btn.primary {
    background: linear-gradient(135deg, #3b82f6, #2563eb);
    color: white;
    border-color: #3b82f6;
}
.action-btn.primary .icon {
    background: rgba(255,255,255,0.2);
}
.action-btn.primary:hover {
    background: linear-gradient(135deg, #2563eb, #1e40af);
    color: white;
}

/* ═══════════════════════════════════════════════════════════
   شارات
   ═══════════════════════════════════════════════════════════ */
.chip {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 4px 12px;
    background: #eff6ff;
    color: #1e40af;
    border-radius: 20px;
    font-size: 0.82rem;
    font-weight: 500;
    margin: 3px 3px 3px 0;
}
.chip.green {
    background: #d1fae5;
    color: #065f46;
}
.chip.orange {
    background: #fed7aa;
    color: #9a3412;
}
.chip.purple {
    background: #e9d5ff;
    color: #6b21a8;
}

/* ═══════════════════════════════════════════════════════════
   الجوال
   ═══════════════════════════════════════════════════════════ */
@media (max-width: 768px) {
    .school-header {
        padding: 20px;
        text-align: center;
        justify-content: center;
    }
    .school-header-info { text-align: center; }
    .school-header-meta { justify-content: center; }
    .school-logo { width: 80px; height: 80px; }
    .school-header-info h1 { font-size: 1.4rem; }

    .info-row { flex-direction: column; gap: 4px; }
    .info-label { width: 100%; }

    .action-grid { grid-template-columns: repeat(2, 1fr); }
    .data-table { font-size: 0.8rem; }
    .data-table thead th, .data-table tbody td { padding: 8px 6px; }
}
</style>

<div class="span10 main-content">

    <!-- ═══════════════ رأس المدرسة ═══════════════ -->
    <div class="school-header">
        <div class="school-logo">
            <?php if (!empty($school['logo']) && file_exists('../' . $school['logo'])): ?>
                <img src="<?php echo h('../' . $school['logo']); ?>" alt="شعار">
            <?php else: ?>
                <div class="placeholder">🏫</div>
            <?php endif; ?>
        </div>
        <div class="school-header-info">
            <h1><?php echo h($school['school_name']); ?></h1>
            <div class="school-header-meta">
                <?php if (!empty($school['school_code'])): ?>
                    <span>🔖 <?php echo h($school['school_code']); ?></span>
                <?php endif; ?>
                <?php if (!empty($school['city'])): ?>
                    <span>📍 <?php echo h($school['city']); ?></span>
                <?php endif; ?>
                <?php if (!empty($school['phone']) || !empty($school['mobile'])): ?>
                    <span>📞 <?php echo h($school['phone'] ?: $school['mobile']); ?></span>
                <?php endif; ?>
                <?php if ($HAS_SCHOOL('is_active')): ?>
                    <span class="status-badge <?php echo $school['is_active'] ? 'active' : 'inactive'; ?>">
                        <?php echo $school['is_active'] ? '✅ نشطة' : '⏸️ موقوفة'; ?>
                    </span>
                <?php endif; ?>
            </div>
        </div>
        <div style="display:flex;flex-direction:column;gap:8px">
            <?php if ($is_super): ?>
                <a href="school_edit.php?id=<?php echo (int)$school_id; ?>" 
                   class="btn" 
                   style="background:white;color:#2563eb;font-weight:600">
                    ✏️ تعديل المدرسة
                </a>
            <?php endif; ?>
            <a href="schools.php" class="btn" 
               style="background:rgba(255,255,255,0.2);color:white;border:none">
                ↩ رجوع للقائمة
            </a>
        </div>
    </div>

    <!-- ═══════════════ الإحصائيات ═══════════════ -->
    <div class="stats-grid">
        <div class="stat-card blue">
            <div class="stat-icon">👥</div>
            <div class="stat-value"><?php echo number_format($stats['students']); ?></div>
            <div class="stat-label">إجمالي الطلاب</div>
            <div class="stat-sub">
                ♂ <?php echo $stats['students_m']; ?>
                · ♀ <?php echo $stats['students_f']; ?>
            </div>
        </div>

        <div class="stat-card green">
            <div class="stat-icon">📚</div>
            <div class="stat-value"><?php echo number_format($stats['classes']); ?></div>
            <div class="stat-label">الفصول</div>
        </div>

        <div class="stat-card purple">
            <div class="stat-icon">🧩</div>
            <div class="stat-value"><?php echo number_format($stats['sections']); ?></div>
            <div class="stat-label">المراحل / الشعب</div>
        </div>

        <div class="stat-card orange">
            <div class="stat-icon">💰</div>
            <div class="stat-value"><?php echo money($stats['fees_total']); ?></div>
            <div class="stat-label">إجمالي الرسوم</div>
        </div>

        <div class="stat-card pink">
            <div class="stat-icon">✅</div>
            <div class="stat-value" style="color:#10b981">
                <?php echo money($stats['fees_paid']); ?>
            </div>
            <div class="stat-label">المدفوع</div>
        </div>

        <div class="stat-card red">
            <div class="stat-icon">⏳</div>
            <div class="stat-value" style="color:#ef4444">
                <?php echo money($stats['fees_unpaid']); ?>
            </div>
            <div class="stat-label">المتبقي</div>
        </div>
    </div>

    <!-- ═══════════════ أزرار الإجراءات السريعة ═══════════════ -->
    <div class="action-grid">
        <a href="students.php?school_id=<?php echo (int)$school_id; ?>" class="action-btn primary">
            <span class="icon">👥</span>
            <span>قائمة الطلاب</span>
        </a>
        <a href="student_add.php?school_id=<?php echo (int)$school_id; ?>" class="action-btn">
            <span class="icon">➕</span>
            <span>إضافة طالب</span>
        </a>
        <a href="classes.php?school_id=<?php echo (int)$school_id; ?>" class="action-btn">
            <span class="icon">📚</span>
            <span>الفصول</span>
        </a>
        <a href="sections.php?school_id=<?php echo (int)$school_id; ?>" class="action-btn">
            <span class="icon">🧩</span>
            <span>المراحل</span>
        </a>
        <a href="fees.php?school_id=<?php echo (int)$school_id; ?>" class="action-btn">
            <span class="icon">💼</span>
            <span>الرسوم</span>
        </a>
        <a href="student_fees.php?school_id=<?php echo (int)$school_id; ?>" class="action-btn">
            <span class="icon">🧾</span>
            <span>رسوم الطلاب</span>
        </a>
    </div>

    <!-- ═══════════════ التفاصيل في شبكة ═══════════════ -->
    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(400px,1fr));gap:16px">

        <!-- معلومات الاتصال -->
        <div class="info-card">
            <h4>📞 معلومات الاتصال</h4>

            <?php
            $info_items = array(
                'phone'           => array('📞', 'الهاتف'),
                'mobile'          => array('📱', 'الجوال'),
                'email'           => array('✉️', 'البريد الإلكتروني'),
                'address'         => array('🏠', 'العنوان'),
                'city'            => array('📍', 'المدينة'),
                'country'         => array('🌍', 'الدولة'),
                'school_code'     => array('🔖', 'رمز المدرسة'),
                'established_year'=> array('📅', 'سنة التأسيس'),
                'students_limit'  => array('👥', 'الحد الأقصى للطلاب'),
                'sort_order'      => array('🔢', 'الترتيب'),
            );

            foreach ($info_items as $field => $meta):
                if (!$HAS_SCHOOL($field)) continue;
                $val = isset($school[$field]) ? $school[$field] : '';
                if ($val === '' || $val === null) continue;
            ?>
            <div class="info-row">
                <div class="info-label">
                    <span><?php echo $meta[0]; ?></span>
                    <span><?php echo $meta[1]; ?></span>
                </div>
                <div class="info-value">
                    <?php if ($field === 'email'): ?>
                        <a href="mailto:<?php echo h($val); ?>" style="direction:ltr;text-align:left;display:inline-block">
                            <?php echo h($val); ?>
                        </a>
                    <?php elseif ($field === 'phone' || $field === 'mobile'): ?>
                        <a href="tel:<?php echo h($val); ?>" style="direction:ltr;display:inline-block">
                            <?php echo h($val); ?>
                        </a>
                    <?php else: ?>
                        <?php echo h($val); ?>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>

            <?php if (!$HAS_SCHOOL('phone') && !$HAS_SCHOOL('mobile') && !$HAS_SCHOOL('email')): ?>
                <div class="info-value muted" style="text-align:center;padding:20px">
                    لا توجد بيانات اتصال
                </div>
            <?php endif; ?>
        </div>

        <!-- إدارة المدرسة -->
        <div class="info-card">
            <h4>👔 إدارة المدرسة</h4>

            <?php if ($HAS_SCHOOL('principal_name') && !empty($school['principal_name'])): ?>
            <div class="info-row">
                <div class="info-label">
                    <span>👤</span>
                    <span>اسم المدير</span>
                </div>
                <div class="info-value"><?php echo h($school['principal_name']); ?></div>
            </div>
            <?php endif; ?>

            <?php if ($HAS_SCHOOL('principal_phone') && !empty($school['principal_phone'])): ?>
            <div class="info-row">
                <div class="info-label">
                    <span>📱</span>
                    <span>جوال المدير</span>
                </div>
                <div class="info-value">
                    <a href="tel:<?php echo h($school['principal_phone']); ?>" style="direction:ltr;display:inline-block">
                        <?php echo h($school['principal_phone']); ?>
                    </a>
                </div>
            </div>
            <?php endif; ?>

            <?php if ($HAS_SCHOOL('created_at') && !empty($school['created_at'])): ?>
            <div class="info-row">
                <div class="info-label">
                    <span>📅</span>
                    <span>تاريخ الإضافة</span>
                </div>
                <div class="info-value"><?php echo h($school['created_at']); ?></div>
            </div>
            <?php endif; ?>

            <?php if (!$HAS_SCHOOL('principal_name') || empty($school['principal_name'])): ?>
                <div class="info-value muted" style="text-align:center;padding:20px">
                    لم تُدخَل بيانات المدير بعد
                </div>
            <?php endif; ?>
        </div>

    </div>

    <!-- ═══════════════ المراحل ═══════════════ -->
    <?php if (!empty($sections_list)): ?>
    <div class="info-card" style="margin-top:16px">
        <h4 style="display:flex;justify-content:space-between;align-items:center">
            <span>🧩 المراحل / الشعب (<?php echo count($sections_list); ?>)</span>
            <a href="sections.php?school_id=<?php echo (int)$school_id; ?>" 
               class="btn" style="padding:6px 14px;font-size:0.85rem">
                إدارة المراحل ←
            </a>
        </h4>

        <div style="display:flex;flex-wrap:wrap;gap:8px">
            <?php foreach ($sections_list as $sec): 
                $sec_name = isset($sec['section_name']) ? $sec['section_name'] 
                          : (isset($sec['name']) ? $sec['name'] : '—');
            ?>
                <span class="chip green">
                    🧩 <?php echo h($sec_name); ?>
                </span>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- ═══════════════ الفصول ═══════════════ -->
    <?php if (!empty($classes_list)): ?>
    <div class="info-card" style="margin-top:16px">
        <h4 style="display:flex;justify-content:space-between;align-items:center">
            <span>📚 الفصول (<?php echo count($classes_list); ?>)</span>
            <a href="classes.php?school_id=<?php echo (int)$school_id; ?>" 
               class="btn" style="padding:6px 14px;font-size:0.85rem">
                إدارة الفصول ←
            </a>
        </h4>

        <table class="data-table">
            <thead>
                <tr>
                    <th width="50">#</th>
                    <th>اسم الفصل</th>
                    <th width="120">عدد الطلاب</th>
                </tr>
            </thead>
            <tbody>
                <?php $i = 1; foreach ($classes_list as $cl): ?>
                <tr>
                    <td><?php echo $i++; ?></td>
                    <td><strong><?php echo h($cl['class_name']); ?></strong></td>
                    <td>
                        <span class="chip blue" style="background:#dbeafe;color:#1e40af">
                            👥 <?php echo (int)$cl['students_count']; ?>
                        </span>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>

    <!-- ═══════════════ أحدث الطلاب ═══════════════ -->
    <?php if (!empty($recent_students)): ?>
    <div class="info-card" style="margin-top:16px">
        <h4 style="display:flex;justify-content:space-between;align-items:center">
            <span>🆕 أحدث الطلاب المضافين</span>
            <a href="students.php?school_id=<?php echo (int)$school_id; ?>" 
               class="btn" style="padding:6px 14px;font-size:0.85rem">
                عرض الكل ←
            </a>
        </h4>

        <table class="data-table">
            <thead>
                <tr>
                    <th width="50">#</th>
                    <th>رقم الطالب</th>
                    <th>الاسم</th>
                    <th width="120">إجراء</th>
                </tr>
            </thead>
            <tbody>
                <?php $i = 1; foreach ($recent_students as $st): 
                    $full = student_full_name_view($st);
                    if ($full === '') $full = '—';
                ?>
                <tr>
                    <td><?php echo $i++; ?></td>
                    <td><code><?php echo h($st['student_code']); ?></code></td>
                    <td>
                        <strong style="color:#1e40af">
                            <?php echo h($full); ?>
                        </strong>
                    </td>
                    <td>
                        <a href="student_view.php?id=<?php echo (int)$st['student_id']; ?>"
                           class="btn btn-sm" style="padding:4px 10px;font-size:0.78rem">
                            👁 عرض
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>

    <!-- ═══════════════ ملاحظات ═══════════════ -->
    <?php if ($HAS_SCHOOL('notes') && !empty($school['notes'])): ?>
    <div class="info-card" style="margin-top:16px">
        <h4>📝 ملاحظات</h4>
        <div style="color:#334155;line-height:1.7;white-space:pre-wrap">
            <?php echo h($school['notes']); ?>
        </div>
    </div>
    <?php endif; ?>

</div>

<?php require_once('includes/footer.php'); ?>
</html>